﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using ServerMonitor.Models;
using System.Diagnostics;
using System.Net;
using System.Data.SqlClient;
using System.IO;
using System.Globalization;
using ServerMonitor.Common;
using System.Threading;
using System.Runtime.InteropServices;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Text.RegularExpressions;

namespace ServerMonitor
{
    public partial class Form1 : Form
    { 
        //全局 
        string ip = ""; 
        PerformanceCounter pcCpuLoad;
        public Models.GlobalSetting setting = new GlobalSetting();
        Thread thread;

        public Form1()
        { 
            try
            {
                pcCpuLoad = new PerformanceCounter("Processor", "% Processor Time", "_Total");
                InitializeComponent(); 
                Common.LogHelper.WriteLog(">>>>>>>>>>>>>>>>>>>>监控程序启动<<<<<<<<<<<<<<<<<<<<", "System"); 
                ip = GetHostIp(); 
                dataGridView1.AutoGenerateColumns = false;
                this.FormClosing += new FormClosingEventHandler(Form1_FormClosing);
                try
                {
                    setting = Common.ObjectHelper.ReadListXml();
                }
                catch (Exception ex) { }
//                LoadData();
                InvokeData();
                MonitorStart(); 
                thread = new Thread(new ThreadStart(DataGet));
                thread.Start();
                WarningTimer.Interval = 1000 * 60 * setting.Interval;//每多长时间检索一次 
                this.cbOff.Checked = setting.SysAlarm;
                //btStartAll_Click(null, null);//重启后启动所有监控程序 
            }
            catch (Exception ex)
            { 
                Common.LogHelper.WriteLog(ex.Message.ToString(), ex.Source);
            }
        }

        void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            // 注意判断关闭事件reason来源于窗体按钮，否则用菜单退出时无法退出!
            if (e.CloseReason == CloseReason.UserClosing)
            {
                //取消"关闭窗口"事件
                e.Cancel = true; // 取消关闭窗体  
                //使关闭时窗口向右下角缩小的效果
                this.WindowState = FormWindowState.Minimized;
                this.notifyIcon1.Visible = true;
                //this.m_cartoonForm.CartoonClose();
                this.Hide();
                return;
            } 
        }

        public void DataGet()
        {
            while (true)
            {
                setting.Pds.Where(a => a.Memo != null && a.Memo.Equals("服务器状态")).ToList().ForEach(a =>
                {
                    a.Responding = (NetWorkHelper.Pinging(a.ProcessName, 2) ? "运行中" : "停止运行");
                });
                Thread.Sleep(1000 * 60 * 3);//3分钟检索一次
            }
        }


        /// <summary>
        /// 获取本机Ip
        /// </summary>
        /// <returns></returns>
        private string GetHostIp()
        {
            var urlList = new List<string>
            {
                "http://ip.qq.com/",
                "http://pv.sohu.com/cityjson?ie=utf-8",
                "http://ip.taobao.com/service/getIpInfo2.php?ip=myip"
            };
            var tempip = "";
            foreach (var a in urlList)
            {
                try
                {
                    var req = WebRequest.Create(a);
                    req.Timeout = 20000;
                    var response = req.GetResponse();
                    var resStream = response.GetResponseStream();
                    if (resStream != null)
                    {
                        var sr = new StreamReader(resStream, Encoding.UTF8);
                        var htmlinfo = sr.ReadToEnd();
                        //匹配IP的正则表达式
                        var r = new Regex("((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)\\.){3}(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|[1-9])", RegexOptions.None);
                        var mc = r.Match(htmlinfo);
                        //获取匹配到的IP
                        tempip = mc.Groups[0].Value;
                        resStream.Close();
                        sr.Close();
                        response.Close();
                        // response.Dispose();
                    }
                    return tempip;
                }
                catch (Exception err)
                {
                    Console.WriteLine("当前探测URL:" + a + ",错误描述：" + err.ToString());
                }
            }
            return tempip;
        }
         
        private void MonitorStart()
        {
            NetworkMonitorSM sm = new NetworkMonitorSM();
            sm.callback += MonitorCallBack;
            sm.StartMonitor();
        }

        private void MonitorCallBack(MonitorInfo info)
        {  
            for (int i = 0; i < dataGridView1.Rows.Count; i++)
            {
                var fangxiang = dataGridView1.Rows[i].Cells[2].Value.ToString();
                if (fangxiang.Equals("上行"))
                {
                    dataGridView1.Rows[i].Cells[5].Value = info.GetKbs(fangxiang) + "KB/s";
                    //更新到实体
                    var temp = setting.Pds.SingleOrDefault(a => a.ProcessName == fangxiang);
                    if (temp != null)
                    {
                        temp.Responding = info.GetKbs(fangxiang);
                    }
                }
                else if (fangxiang.Equals("下行"))
                {
                    dataGridView1.Rows[i].Cells[5].Value = info.GetKbs(fangxiang) + "KB/s";
                    var temp = setting.Pds.SingleOrDefault(a => a.ProcessName == fangxiang);
                    if (temp != null)
                    {
                        temp.Responding = info.GetKbs(fangxiang); 
                    }
                }
            }
        }

        /// <summary>
        /// 选择需要监控的进程
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btAddMonitor_Click(object sender, EventArgs e)
        {
            try
            {
                Form f = new SelectMonitorItem(this);
                f.FormClosed += new FormClosedEventHandler(f_FormClosed);
                f.ShowDialog();
            }
            catch (Exception ex)
            { }
        }

        void f_FormClosed(object sender, FormClosedEventArgs e)
        { 
            if ((sender as SelectMonitorItem).DialogResult == DialogResult.OK)
            {
                InvokeData();
                timer1_Tick(null, null);
            }
        }

        /// <summary>
        /// 定时检索
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer1_Tick(object sender, EventArgs e)
        {
            try
            {
                toolStripProgressBar1.Value = 0;//进度10 
                string stopProcess = string.Empty;
                List<KeyValuePair<string, DateTime>> PathData = new List<KeyValuePair<string, DateTime>>();
                //List<string> process = new List<string>();
                Process[] pro = Process.GetProcesses();
                foreach (var item in pro)
                {
                    try
                    {
                        if (!PathData.Exists(a => a.Key.Equals(item.MainModule.FileName)))
                        {
                            PathData.Add(new KeyValuePair<string, DateTime>(item.MainModule.FileName, item.StartTime));
                        } 
                    }
                    catch (Exception ex) { }
                }
                toolStripProgressBar1.Value = 5;//进度10
                for (int i = 0; i < setting.Pds.Count; i++)
                {
                    if (setting.Pds[i].ProcessLavel == 0)
                    {
                        KeyValuePair<string, DateTime> old = PathData.SingleOrDefault(a => a.Key.Equals(setting.Pds[i].ProcessPath)); 
                        if (old.Key == null)
                        {
                            setting.Pds[i].Responding = "停止运行"; 
                        }
                        else
                        {
                            setting.Pds[i].Responding = "运行中";
                            setting.Pds[i].StartTime = old.Value;
                        }
                    }
                } 
                toolStripProgressBar1.Value = 10;//进度10 
                DateTime mTime = GetComputerStartTime();// DateTime.Now.AddMilliseconds(0 - Environment.TickCount); 
                int rows = dataGridView1.Rows.Count; 
                for (int i = 0; i < rows; i++)
                {
                    toolStripProgressBar1.Value = 10 + (rows / 80) * i;//进度20 
                    var cur = setting.Pds.Single(a => a.ProcessPath.Equals(dataGridView1.Rows[i].Cells[6].Value));
                    if (cur.ProcessLavel == 1)
                    {
                        cur.StartTime = mTime;
                    } 
                    //dataGridView1.Rows[i].Cells[0].Value = cur.Monitor == true ? "√" : ""; //监控状态 

                    dataGridView1.Rows[i].Cells[0].Value = cur.Monitor == true ? Image.FromFile("Images/Start1.png") : Image.FromFile("Images/stop1.png");
                    dataGridView1.Rows[i].Cells[3].Value = cur.StartTime.ToString();//开始时间
                    //累计运行时长
                    dataGridView1.Rows[i].Cells[4].Value = (DateTime.Now - cur.StartTime.Value).Days.ToString() + "天" + (DateTime.Now - cur.StartTime.Value).Hours.ToString() + "小时" + (DateTime.Now - cur.StartTime.Value).Minutes.ToString() + "分" + (DateTime.Now - cur.StartTime.Value).Seconds.ToString() + "秒";
                    //特殊监控判断--需更新到内存
                    if (cur.ProcessLavel == 1)
                    {
                        switch (cur.Memo)
                        {
                            case "CPU使用率":
                                // ServerMonitor.Common.SystemInfo.StorageInfo memInfor = Common.SystemInfo.get_StorageInfo();
                                string cc = pcCpuLoad.NextValue().ToString("0.00"); 
                                dataGridView1.Rows[i].Cells[5].Value = cc.Substring(0, cc.IndexOf('.')) + "%";
                                cur.Responding = cc.Substring(0, cc.IndexOf('.'));
                                break; 
                            case "内存使用率":
                                ServerMonitor.Common.SystemInfo.StorageInfo memInfor = Common.SystemInfo.get_StorageInfo();
                                dataGridView1.Rows[i].Cells[5].Value = memInfor.dwMemoryLoad + "%";
                                cur.Responding = memInfor.dwMemoryLoad.ToString();
                                break; 
                            case "数据库连接数":
                                try
                                {
                                    string count = SqlHelper.GetConnectCount(cur.ProcessName, setting.ConStr).Rows[0][0].ToString();
                                    dataGridView1.Rows[i].Cells[5].Value = count;
                                    cur.Responding = count;
                                }
                                catch (Exception ex)
                                {
                                    //MessageBox.Show(ex.Message);
                                }
                                break; 
                            case "磁盘使用率":
                                try
                                {
                                    string syl = new Common.Minfo().GetHardRate(cur.ProcessName).ToString();
                                    dataGridView1.Rows[i].Cells[5].Value = syl + "%";
                                    cur.Responding = syl;
                                }
                                catch (Exception ex)
                                {
                                    //MessageBox.Show(ex.Message);
                                }
                                break;
                            case "服务器状态":
                                try
                                { 
                                    dataGridView1.Rows[i].Cells[5].Value = cur.Responding; 
                                }
                                catch (Exception ex)
                                {
                                    //MessageBox.Show(ex.Message);
                                }
                                break;
                        }
                    }
                    else
                    {
                        dataGridView1.Rows[i].Cells[5].Value = cur.Responding;//运行状态
                    }
                } 
                toolStripProgressBar1.Value = 100;//进度20 
                toolStripStatusLabel1.Text = "UI最新更新时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                toolStripStatusLabel2.Text = "UI更新间隔为:" + timer1.Interval / 1000 + "秒/次";
                toolStripStatusLabel3.Text = "通知发送:" + setting.Interval + "分/次";
                toolStripStatusLabel4.Text = "通知共发送:" + setting.Count + "次";
                toolStripStatusLabel5.Text = "报警每" + setting.Interval + "分钟检索1次";
                toolStripStatusLabel6.Text = "监控" + setting.Pds.Count(a => a.ProcessLavel == 0) + "个程序"; 
            }
            catch (Exception ex) 
            {

            }
        }

        #region 停止使用
        /// <summary>
        /// 绑定数据
        /// </summary>
        private void LoadData()
        {
            setting.Pds.RemoveAll(a => a.ProcessLavel == 1);
            Models.ProcessDescribe temp;
            #region 添加CPU,磁盘，内存监控
            //CPU 
            string cc = pcCpuLoad.NextValue().ToString("0.00");
            temp = new ProcessDescribe
            {
                Monitor = true,
                Memo = "CPU使用率",
                ProcessName = "CPU",
                StartTime = DateTime.Now,
                Responding = "0",
                ProcessPath = "CPU使用率",
                ProcessLavel = 1
            };
            setting.Pds.Add(temp);

            //内存
            temp = new ProcessDescribe
            {
                Monitor = true,
                Memo = "内存使用率",
                ProcessName = "内存",
                StartTime = DateTime.Now,
                Responding = "0",
                ProcessPath = "内存使用率",
                ProcessLavel = 1
            };
            setting.Pds.Add(temp);

            //磁盘  
            DriveInfo[] info = DriveInfo.GetDrives();
            string Pan = string.Empty;
            foreach (var item in info)
            {
                try
                {
                    if (item.DriveType == DriveType.Fixed)
                    {
                        Pan = item.Name.Substring(0, 1);
                        //Common.LogHelper.WriteLog(Pan, "");
                        temp = new ProcessDescribe
                        {
                            Monitor = true,
                            Memo = "磁盘使用率",
                            ProcessName = Pan,
                            StartTime = DateTime.Now,
                            Responding = "0",
                            ProcessPath = Pan + "盘存使用率",
                            ProcessLavel = 1
                        };
                        setting.Pds.Add(temp);
                    }
                }
                catch (Exception ex) { }
            }

            #endregion

            #region 添加流量监控
            temp = new ProcessDescribe
            {
                Monitor = true,
                Memo = "流量监控",
                ProcessName = "上行",
                StartTime = DateTime.Now,
                Responding = "0",//new MonitorInfo().GetKbs("上行"),
                ProcessPath = "上行流量",
                ProcessLavel = 1
            };
            setting.Pds.Add(temp);


            temp = new ProcessDescribe
            {
                Monitor = true,
                Memo = "流量监控",
                ProcessName = "下行",
                StartTime = DateTime.Now,
                Responding = "0",//new  MonitorInfo().GetKbs("下行"),
                ProcessPath = "下行流量",
                ProcessLavel = 1
            };
            setting.Pds.Add(temp);







            #endregion
            
            #region 添加数据库监控
            if (!string.IsNullOrEmpty(setting.DbNames.Trim()))
            {
                DataTable dt = SqlHelper.GetConnectCount(setting.DbNames, setting.ConStr);
                if (dt != null && dt.Rows.Count > 0)
                {
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        //DB

                        temp = new ProcessDescribe
                        {
                            Monitor = true,
                            Memo = "数据库连接数",
                            ProcessName = dt.Rows[i]["Db"].ToString(),
                            StartTime = DateTime.Now,
                            Responding = dt.Rows[i]["Count"].ToString(),
                            ProcessPath = dt.Rows[i]["Db"].ToString() + "库连接数",
                            ProcessLavel = 1
                        };
                        setting.Pds.Add(temp);

                    }
                }
            }
            #endregion



            #region 添加服务器监控


            if (!string.IsNullOrEmpty(setting.Ips.Trim()))
            {
                // bool connect = false;
                setting.Ips.Split(',').ToList().ForEach(a =>
                {
                    //connect = NetWorkHelper.Pinging(a, 3);
                    temp = new ProcessDescribe
                    {
                        Monitor = true,
                        Memo = "服务器状态",
                        ProcessName = a,
                        StartTime = DateTime.Now,
                        Responding = "运行中",
                        ProcessPath = a + "运行状态",
                        ProcessLavel = 1
                    };
                    setting.Pds.Add(temp);

                });
            }

            #endregion



            setting.Pds = setting.Pds.OrderByDescending(a => a.ProcessLavel).OrderBy(a => a.Responding).ToList();
            #region 注释
            //this.dataGridView1.ColumnCount = 7;
            //this.dataGridView1.Columns[0].HeaderText = "状态";


            //this.dataGridView1.Columns[1].HeaderText = "程序名称";
            //this.dataGridView1.Columns[2].HeaderText = "进程名称";
            //// this.dataGridView1.Columns[3].HeaderText = "主窗口名称";
            //this.dataGridView1.Columns[3].HeaderText = "开始运行时间";
            //this.dataGridView1.Columns[4].HeaderText = "累计运行时间";
            //this.dataGridView1.Columns[5].HeaderText = "状态";
            //this.dataGridView1.Columns[6].HeaderText = "程序路径";

            //this.dataGridView1.Columns[0].Name = "Monitor";
            //this.dataGridView1.Columns[1].Name = "Memo";
            //this.dataGridView1.Columns[2].Name = "ProcessName";
            ////this.dataGridView1.Columns[3].Name = "MainWindowTitle";
            //this.dataGridView1.Columns[3].Name = "StartTime";
            //this.dataGridView1.Columns[4].Name = "TotalTime";
            //this.dataGridView1.Columns[5].Name = "Responding";
            //this.dataGridView1.Columns[6].Name = "ProcessPath";

            //this.dataGridView1.Columns[0].Width = 60;
            //this.dataGridView1.Columns[1].Width = 100;
            //this.dataGridView1.Columns[2].Width = 100;
            ////this.dataGridView1.Columns[3].Width = 100;
            //this.dataGridView1.Columns[3].Width = 120;
            //this.dataGridView1.Columns[4].Width = 120;
            //this.dataGridView1.Columns[5].Width = 100;
            //this.dataGridView1.Columns[6].Width = 300;
            #endregion

            this.dataGridView1.Rows.Clear();
            foreach (var map in setting.Pds)
            { 
                TimeSpan t = (DateTime.Now - map.StartTime.Value);//时间差
                dataGridView1.Rows.Add(new object[] 
                { 
                   
                    map.Monitor==true?  Image.FromFile("Images/Start1.png"):Image.FromFile("Images/stop1.png"),
                    map.Memo, 
                    map.ProcessName,
                    //map.MainWindowTitle, 
                    (map.ProcessLavel==0)?map.StartTime.ToString():"",
                    (map.ProcessLavel==0)?(map.StartTime==null?"":t.Days.ToString()+"天"+t.Hours.ToString()+"小时"+t.Minutes.ToString()+"分"+t.Seconds.ToString()+"秒"):"",
                    map.Responding,
                    map.ProcessPath
                });
            }

        }
        #endregion

        private void InvokeData()
        {
            try
            {
                timer1.Stop();
                WarningTimer.Stop(); 
                //this.Invoke(new Action(delegate
                //{ 
                    setting.Pds.RemoveAll(a => a.ProcessLavel == 1);
                    Models.ProcessDescribe temp;
                    #region 添加CPU,磁盘，内存监控
                    //CPU 
                    string cc = pcCpuLoad.NextValue().ToString("0.00");
                    temp = new ProcessDescribe
                    {
                        Monitor = true,
                        Memo = "CPU使用率",
                        ProcessName = "CPU",
                        StartTime = DateTime.Now,
                        Responding = "0",
                        ProcessPath = "CPU使用率",
                        ProcessLavel = 1
                    };
                    setting.Pds.Add(temp); 
                    //内存
                    temp = new ProcessDescribe
                    {
                        Monitor = true,
                        Memo = "内存使用率",
                        ProcessName = "内存",
                        StartTime = DateTime.Now,
                        Responding = "0",
                        ProcessPath = "内存使用率",
                        ProcessLavel = 1
                    };
                    setting.Pds.Add(temp); 
                    //磁盘  
                    DriveInfo[] info = DriveInfo.GetDrives();
                    string Pan = string.Empty;
                    foreach (var item in info)
                    {
                        try
                        {
                            if (item.DriveType == DriveType.Fixed)
                            {
                                Pan = item.Name.Substring(0, 1);
                                temp = new ProcessDescribe
                                {
                                    Monitor = true,
                                    Memo = "磁盘使用率",
                                    ProcessName = Pan,
                                    StartTime = DateTime.Now,
                                    Responding = "0",
                                    ProcessPath = Pan + "盘存使用率",
                                    ProcessLavel = 1
                                };
                                setting.Pds.Add(temp);
                            }
                        }
                        catch (Exception ex) { }
                    } 
                    #endregion 

                    #region 添加流量监控
                    temp = new ProcessDescribe
                    {
                        Monitor = true,
                        Memo = "流量监控",
                        ProcessName = "上行",
                        StartTime = DateTime.Now,
                        Responding = "0",//new MonitorInfo().GetKbs("上行"),
                        ProcessPath = "上行流量",
                        ProcessLavel = 1
                    };
                    setting.Pds.Add(temp);


                    temp = new ProcessDescribe
                    {
                        Monitor = true,
                        Memo = "流量监控",
                        ProcessName = "下行",
                        StartTime = DateTime.Now,
                        Responding = "0",//new  MonitorInfo().GetKbs("下行"),
                        ProcessPath = "下行流量",
                        ProcessLavel = 1
                    };
                    setting.Pds.Add(temp);







                    #endregion
                     
                    #region 添加数据库监控

                    if (!string.IsNullOrEmpty(setting.DbNames.Trim()))
                    {
                        DataTable dt = SqlHelper.GetConnectCount(setting.DbNames, setting.ConStr);
                        if (dt != null && dt.Rows.Count > 0)
                        {
                            for (int i = 0; i < dt.Rows.Count; i++)
                            {
                                //DB

                                temp = new ProcessDescribe
                                {
                                    Monitor = true,
                                    Memo = "数据库连接数",
                                    ProcessName = dt.Rows[i]["Db"].ToString(),
                                    StartTime = DateTime.Now,
                                    Responding = dt.Rows[i]["Count"].ToString(),
                                    ProcessPath = dt.Rows[i]["Db"].ToString() + "库连接数",
                                    ProcessLavel = 1
                                };
                                setting.Pds.Add(temp);

                            }
                        }
                    }
                    #endregion
                     
                    #region 添加服务器监控


                    if (!string.IsNullOrEmpty(setting.Ips.Trim()))
                    {
                        //bool connect = false;
                        setting.Ips.Split(',').ToList().ForEach(a =>
                        {
                            // connect = NetWorkHelper.Pinging(a, 3);
                            temp = new ProcessDescribe
                            {
                                Monitor = true,
                                Memo = "服务器状态",
                                ProcessName = a,
                                StartTime = DateTime.Now,
                                Responding = "运行中",
                                ProcessPath = a + "运行状态",
                                ProcessLavel = 1
                            };
                            setting.Pds.Add(temp);

                        });
                    }

                    #endregion
                     
                    setting.Pds = setting.Pds.OrderByDescending(a => a.ProcessLavel).OrderBy(a => a.Responding).ToList();

                    #region 注释
                    //this.dataGridView1.ColumnCount = 7; 
                    //this.dataGridView1.Columns[0].HeaderText = "状态";
                    //this.dataGridView1.Columns[1].HeaderText = "程序名称";
                    //this.dataGridView1.Columns[2].HeaderText = "进程名称";
                    //// this.dataGridView1.Columns[3].HeaderText = "主窗口名称";
                    //this.dataGridView1.Columns[3].HeaderText = "开始运行时间";
                    //this.dataGridView1.Columns[4].HeaderText = "累计运行时间";
                    //this.dataGridView1.Columns[5].HeaderText = "状态";
                    //this.dataGridView1.Columns[6].HeaderText = "程序路径"; 
                    //this.dataGridView1.Columns[0].Name = "Monitor";
                    //this.dataGridView1.Columns[1].Name = "Memo";
                    //this.dataGridView1.Columns[2].Name = "ProcessName";
                    ////this.dataGridView1.Columns[3].Name = "MainWindowTitle";
                    //this.dataGridView1.Columns[3].Name = "StartTime";
                    //this.dataGridView1.Columns[4].Name = "TotalTime";
                    //this.dataGridView1.Columns[5].Name = "Responding";
                    //this.dataGridView1.Columns[6].Name = "ProcessPath"; 
                    //this.dataGridView1.Columns[0].Width = 60;
                    //this.dataGridView1.Columns[1].Width = 100;
                    //this.dataGridView1.Columns[2].Width = 100;
                    ////this.dataGridView1.Columns[3].Width = 100;
                    //this.dataGridView1.Columns[3].Width = 120;
                    //this.dataGridView1.Columns[4].Width = 120;
                    //this.dataGridView1.Columns[5].Width = 100;
                    //this.dataGridView1.Columns[6].Width = 300; 
                    #endregion

                    this.dataGridView1.Rows.Clear();
                    string con = tbSearch.Text.Trim().ToLower();//搜索条件
                    foreach (var map in 
                        setting.Pds.Where(a=>a.Memo.ToLower().Contains(con)||a.ProcessName.ToLower().Contains(con)||a.ProcessPath.Contains(con))
)
                    {
                        TimeSpan t = (DateTime.Now - map.StartTime.Value);//时间差
                        dataGridView1.Rows.Add(new object[] 
                        {
                                                   
                            map.Monitor==true? Image.FromFile("Images/Start1.png"):Image.FromFile("Images/stop1.png"),
                            map.Memo, 
                            map.ProcessName,
                            //map.MainWindowTitle, 
                            (map.ProcessLavel==0)?map.StartTime.ToString():"",
                            (map.ProcessLavel==0)?(map.StartTime==null?"":t.Days.ToString()+"天"+t.Hours.ToString()+"小时"+t.Minutes.ToString()+"分"+t.Seconds.ToString()+"秒"):"",
                            map.Responding,
                            map.ProcessPath
                        });
                    }
              //  })); 
                timer1.Start();
                WarningTimer.Start();
            }
            catch (Exception ex) { }
        }

        /// <summary>
        /// 全部停止监控
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btAllEnd_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < setting.Pds.Count; i++)
            {
                setting.Pds[i].Monitor = false;
            }
            //BindData();
            Common.LogHelper.Log("停止所有的监控程序"); 
            timer1_Tick(null, null);
        }
        /// <summary>
        /// 全部开始监控
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btAllStart_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < setting.Pds.Count; i++)
            {
                setting.Pds[i].Monitor = true;
            } 
            Common.LogHelper.Log("开启所有的监控程序"); 
            timer1_Tick(null, null);
        }
         
        List<string> oldMessage = new List<string>();//存储最后发送的消息
        int HasSendCount = 0;//已发送次数 
        /// <summary>
        /// 定时报警程序
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param> 
        private void WarningTimer_Tick(object sender, EventArgs e)
        { 
            List<string> msgList = new List<string>();
            string Message = string.Empty; 
            List<KeyValuePair<string, string>> SMSList = new List<KeyValuePair<string, string>>(); 
            //主监控程序状态报警信息  
            var mainPros = setting.Pds.Where(a => a.ProcessLavel == 1).ToList();
            int result = 1; 
            string Qianzhui = "\r\n";
            foreach (var item in mainPros)
            {
                switch (item.Memo)
                {
                    case "CPU使用率":
                        result = Convert.ToInt32((item.Responding));
                        if (result > setting.CpuAlarm && item.Monitor)
                        {
                            Message += Qianzhui + "CPU：" + item.Memo + "[" + item.ProcessName + "]" + ",当前使用率达到" + result + "%,超过设定值" + setting.CpuAlarm + "%";
                            //SMSList.Add(new KeyValuePair<string,string>("134608","【扬天科技】" + ip + "在" + DateTime.Now.ToString() + "CPU使用率超过" + setting.CpuAlarm + "，请及时处理！"));//SMS
                            SMSList.Add(new KeyValuePair<string, string>("134608", "#IPServer#=" + ip + ":&#DateTime#=" + DateTime.Now + "&#SourceType#=CPU使用率&#MaxValue#=" + setting.CpuAlarm + "%"));//SMS


                            msgList.Add(item.ProcessName + item.ProcessPath);
                        }
                        break;

                    case "内存使用率":
                        result = Convert.ToInt32((item.Responding));
                        if (result > setting.MemoryAlarm && item.Monitor)
                        {
                            Message += Qianzhui + "内存：" + item.Memo + "[" + item.ProcessName + "]" + ",当前使用率达到" + result + "%,超过设定值" + setting.MemoryAlarm + "%";
                            //SMSList.Add(new KeyValuePair<string,string>("134608","【扬天科技】" + ip + "在" + DateTime.Now.ToString() + "内存使用率超过" + setting.MemoryAlarm + "，请及时处理！"));//SMS
                            SMSList.Add(new KeyValuePair<string, string>("134608", "#IPServer#=" + ip + ":&#DateTime#=" + DateTime.Now + "&#SourceType#=内存使用率&#MaxValue#=" + setting.MemoryAlarm + "%"));//SMS
                            msgList.Add(item.ProcessName + item.ProcessPath);
                        }
                        break;

                    case "数据库连接数":
                        result = Convert.ToInt32((item.Responding));
                        if (result > setting.ConnectCount && item.Monitor)
                        {
                            Message += Qianzhui + "数据库：" + item.Memo + "[" + item.ProcessName + "]" + ",当前连接数达到" + result + ",超过设定值" + setting.ConnectCount;
                            //SMSList.Add(new KeyValuePair<string, string>("134608", "【扬天科技】" + ip + "在" + DateTime.Now.ToString() + item.Memo + "数据库连接数超过" + setting.ConnectCount + "，请及时处理！"));//SMS
                            SMSList.Add(new KeyValuePair<string, string>("134608", "#IPServer#=" + ip + ":&#DateTime#=" + DateTime.Now + "&#SourceType#=" + item.Memo + "库连接数&#MaxValue#=" + setting.ConnectCount));//SMS
                            msgList.Add(item.ProcessName + item.ProcessPath);
                        }
                        break;

                    case "磁盘使用率":
                        result = Convert.ToInt32((item.Responding));
                        if (result > setting.DiskAlarm && item.Monitor)
                        {
                            Message += Qianzhui + "磁盘：" + item.Memo + "[" + item.ProcessName + "]" + ",当前使用率达到" + result + "%,超过设定值" + setting.DiskAlarm + "%";
                            //SMSList.Add(new KeyValuePair<string,string>("134608","【扬天科技】" + ip + "在" + DateTime.Now.ToString() + "磁盘使用率超过" + setting.DiskAlarm + "，请及时处理！"));//SMS
                            SMSList.Add(new KeyValuePair<string, string>("134608", "#IPServer#=" + ip + ":&#DateTime#=" + DateTime.Now + "&#SourceType#=" + item.Memo + "盘使用率&#MaxValue#=" + setting.DiskAlarm + "%"));//SMS
                            msgList.Add(item.ProcessName + item.ProcessPath);
                        }
                        break;

                    case "服务器状态":

                        if (!item.Responding.Equals("运行中") && item.Monitor)
                        {
                            Message += Qianzhui + "服务器：" + item.Memo + "[" + item.ProcessName + "]" + ",停止运行";
                            //SMSList.Add(new KeyValuePair<string,string>("134607","【扬天科技】"+ip+","+item.Memo+"在"+DateTime.Now.ToString()+"发生异常，请及时处理！"));//SMS 
                            SMSList.Add(new KeyValuePair<string, string>("134607", "#IPServer#=" + ip + "，&#programmeName#=" + item.ProcessName + item.Memo + "，&#DateTime#=" + DateTime.Now));
                            msgList.Add(item.ProcessName + item.ProcessPath);
                        }
                        break;

                    case "流量监控":
                        result = Convert.ToInt32((item.Responding));
                        if (item.ProcessName.Equals("上行"))
                        {
                            if (result > setting.UpKbs && item.Monitor)
                            {
                                Message += Qianzhui + "流量监控：" + item.Memo + "[" + item.ProcessName + "]" + "，当前使用量为" + result + "k/s,超过设定值" + setting.UpKbs + "k/s";
                                // SMSList.Add(new KeyValuePair<string,string>("134608","【扬天科技】" + ip + "在" + DateTime.Now.ToString() + "上行流量超过" + setting.UpKbs + "k/s，请及时处理！"));//SMS
                                SMSList.Add(new KeyValuePair<string, string>("134608", "#IPServer#=" + ip + ":&#DateTime#=" + DateTime.Now + "&#SourceType#=上行流量&#MaxValue#=" + setting.UpKbs + "K/S"));//SMS
                                msgList.Add(item.ProcessName + item.ProcessPath);
                            }
                        }
                        else
                        {
                            if (result > setting.DownKbs && item.Monitor)
                            {
                                Message += Qianzhui + "流量监控：" + item.Memo + "[" + item.ProcessName + "]" + "，当前使用量为" + result + "k/s,超过设定值" + setting.DownKbs + "k/s";
                                //SMSList.Add(new KeyValuePair<string,string>("134608","【扬天科技】" + ip + "在" + DateTime.Now.ToString() + "下行流量超过" + setting.DownKbs + "k/s，请及时处理！"));//SMS
                                SMSList.Add(new KeyValuePair<string, string>("134608", "#IPServer#=" + ip + ":&#DateTime#=" + DateTime.Now + "&#SourceType#=下行流量&#MaxValue#=" + setting.DownKbs + "K/S"));//SMS
                                msgList.Add(item.ProcessName + item.ProcessPath);
                            }
                        }
                        break;
                }
            } 
            //根据被监控的程序的运行状态生成报警通知信息，通知到对应负责人
            for (int i = 0; i < setting.Pds.Count; i++)
            {
                if (setting.Pds[i].ProcessLavel == 0)
                {
                    if (setting.Pds[i].Monitor == true && setting.Pds[i].Responding == "停止运行")
                    {
                        Message += Qianzhui + "监控程序：" + setting.Pds[i].Memo + "[" + setting.Pds[i].ProcessName + "]" + ",停止运行";
                        //SMSList.Add(new KeyValuePair<string,string>("134607","【扬天科技】" + ip + "," + setting.Pds[i].Memo + "在" + DateTime.Now.ToString() + "发生异常，请及时处理！"));//SMS
                        SMSList.Add(new KeyValuePair<string, string>("134607", "#IPServer#=" + ip + ":&#programmeName#=" + setting.Pds[i].Memo + "&#DateTime#=" + DateTime.Now));
                        msgList.Add(setting.Pds[i].ProcessName);
                    }
                }
            } 
            #region 发送报警消息
             
            if (!string.IsNullOrEmpty(Message))
            {
                btStartAll_Click(null, null);//重启所有监控程序
                //开始发送消息
                if (ArrayEquals(oldMessage, msgList))
                {
                    if (HasSendCount < setting.Count)
                    {
                        //发送消息 
                        setting.PhoneNumbers.Split(',').ToList().ForEach(a =>
                        {
                            SendSMS(a, SMSList, Message);
                        });
                        HasSendCount += 1;
                    }
                }
                else
                {
                    //发送消息
                    setting.PhoneNumbers.Split(',').ToList().ForEach(a =>
                    {
                        SendSMS(a, SMSList, Message);
                    });
                    HasSendCount += 1;
                }
                oldMessage = msgList;
            }
            else
            {
                oldMessage = msgList;
                HasSendCount = 0;
            }
            #endregion
        }

        /// <summary>
        /// 判断两个数组元素是否相同
        /// </summary>
        /// <param name="a"></param>
        /// <param name="b"></param>
        /// <returns></returns>
        public bool ArrayEquals(List<string> a, List<string> b)
        {
            bool eq = false;
            if (a.Count == b.Count)
            {
                for (int i = 0; i < a.Count; i++)
                {
                    if (!b.Contains(a[i]))
                    {
                        eq = false;
                        break;
                    }
                }
                eq = true;
            }
            else
            {
                eq = false;
            }
            return eq;
        }

        private void btSet_Click(object sender, EventArgs e)
        {
            Form gSetting = new WarningSet(this);
            gSetting.FormClosed += new FormClosedEventHandler(gSetting_FormClosed);
            gSetting.ShowDialog(); 
        }

        void gSetting_FormClosed(object sender, FormClosedEventArgs e)
        {
            InvokeData();
            WarningTimer.Interval = 1000 * 60 * setting.Interval;//每多长时间检索一次
            // toolStripProgressBar1.Value = 0;//进度20
            timer1_Tick(null, null);
        }

        //发送短信
        private void SendSMS(string mobile, List<KeyValuePair<string, string>> SMSList, string txt)
        { 
            txt = "IP:" + ip + txt; 
            if (this.cbOff.Checked)
            {
                Common.LogHelper.WriteLog(txt, mobile);
            }
            else
            {
                Common.LogHelper.WriteLog(txt, mobile); 
                string Sql = "";
                foreach (var item in SMSList)
                {
                    Sql += string.Concat(new string[]
                {
                "INSERT INTO  [SMS_Pool] ([Phone] ,[TempleteID] ,[TempleteContent] ) VALUES ('"+mobile+"', '"+item.Key+"','"+item.Value+"')"    
                });
                } 
                try
                {
                    SqlConnection sqlConnection = new SqlConnection("Server=.;	UID=gps;PWD=123456;Database=sa");
                    SqlCommand sqlCommand = new SqlCommand(Sql, sqlConnection);
                    sqlConnection.Open();
                    int i = sqlCommand.ExecuteNonQuery();
                    sqlConnection.Close();
                    sqlConnection.Dispose();
                    sqlCommand.Dispose(); 
                    Common.LogHelper.WriteLog("警告消息已发出>>>>>>\r\n", mobile); 
                }
                catch (Exception ex)
                {
                    Common.LogHelper.WriteLog("发送警告失败！！！！！！", mobile);
                }
            }
        }

        //打开日志目录
        private void btLog_Click(object sender, EventArgs e)
        {
            string path = Application.StartupPath + "/log/";
            if (Directory.Exists(path) == false)//如果不存
            {
                Directory.CreateDirectory(path);
            }
            System.Diagnostics.Process.Start(path);
            Common.LogHelper.Log("打开日志目录");
        }

        private void btReName_Click(object sender, EventArgs e)
        {
            Form rName = new ReName(this);
            rName.FormClosed += new FormClosedEventHandler(rName_FormClosed);
            rName.ShowDialog();
        }

        void rName_FormClosed(object sender, FormClosedEventArgs e)
        {
            if ((sender as ReName).DialogResult == DialogResult.OK)
            {
                InvokeData();
                timer1_Tick(null, null);
            }
        }
        //启动所有的监控程序
        [STAThread]
        private void btStartAll_Click(object sender, EventArgs e)
        {
            List<string> paths = setting.Pds.Where(a => a.ProcessLavel == 0).Select(a => a.ProcessPath).ToList();
            Process[] pro = Process.GetProcesses();
            List<string> runProcessPath = new List<string>();
            for (int i = 0; i < pro.Count(); i++)
            {
                try
                {
                    runProcessPath.Add(pro[i].MainModule.FileName);
                   // Common.LogHelper.Log("-------------当前系统运行程序：" + pro[i].MainModule.FileName);
                }
                catch (Exception ex) 
                {
                   // MessageBox.Show(ex.Message);
                }
            }
            foreach (var item in paths)
            {
                try
                {
                    if (!runProcessPath.Exists(a => a.Equals(item)))
                    {
                        // MessageBox.Show(item);
                        System.Diagnostics.Process.Start(item); //打开此文件。 
                      //  Common.LogHelper.Log("*************启动程序：" + item);
                    }
                }
                catch (Exception ex) { }
            }
            Common.LogHelper.Log("启动所有被监控的程序");
        }

        public void asdf()
        {
            DataGridViewSelectedRowCollection items = dataGridView1.SelectedRows;
            foreach (DataGridViewRow item in items)
            {
                string pName = item.Cells[2].Value.ToString();
                string pPath = item.Cells[6].Value.ToString(); 
                Process[] temp = Process.GetProcessesByName(pName);//在所有已启动的进程中查找需要的进程； 
                if (temp.Length > 0)//如果查找到
                {
                    foreach (var pro in temp)
                    {
                        if (pro.ProcessName.Equals(pName) && pro.MainModule.FileName.Equals(pPath))
                        {
                            IntPtr handle = pro.MainWindowHandle;
                            SwitchToThisWindow(handle, true); // 激活，显示在最前
                        }
                        else
                        {

                        }
                    }
                }
            }
        }

        #region 系统托盘

        private void 最小化ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Minimized;
            this.notifyIcon1.Visible = true;
            this.Hide();
        }

        private void 最大化ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Maximized;
            this.notifyIcon1.Visible = true;
            this.Show();
        }

        private void 还原ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Show();
            this.WindowState = FormWindowState.Normal;
            this.notifyIcon1.Visible = true;
            //this.m_cartoonForm.CartoonShowNormal();
        }

        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {

            timer1.Stop();
            WarningTimer.Stop();
            timer1.Dispose();
            WarningTimer.Dispose();

            setting.Pds.RemoveAll(a => a.ProcessLavel == 1);

            setting.SysAlarm = cbOff.Checked;

            Common.ObjectHelper.WriteSingleXml(setting);

            Common.LogHelper.WriteLog("<<<<<<<<<<<<<<<<<<<<监控程序退出>>>>>>>>>>>>>>>>>>>>", "System");
            thread.Abort();



            this.notifyIcon1.Visible = false;
            this.Close();
            this.Dispose();
            System.Environment.Exit(System.Environment.ExitCode);

        }
      
        /// <summary>
        /// 双击还原
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (this.Visible)
            {
                this.WindowState = FormWindowState.Minimized;
                this.notifyIcon1.Visible = true;
                this.Hide();
            }
            else
            {
                this.Visible = true;
                this.WindowState = FormWindowState.Normal;
                this.Activate();
            }
        } 
        #endregion

        #region 微信相关

        public string GetAccess_Token()
        {
            string url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx108ef20f45dcbd9d&secret=97e88ee27535b2b951bcc8d876344c20";
            string Account_Token = Utils.HttpHelper.Get(url);


            Token token = JsonConvert.DeserializeObject<Token>(Account_Token);


            return token.access_token;
        }

        /// <summary>
        /// 客服发送消息-POST
        /// </summary>
        /// <returns></returns>
        public string GetKFSend()
        {
            string url = string.Format("https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token={0}", GetAccess_Token());
            return url;
        }

        /// <summary>
        /// 发送文本消息
        /// </summary>
        /// <param name="content"></param>
        /// <returns></returns>
        /// 
        public string SendText(string openid, string content)
        {
            string result = string.Empty;
            if (!string.IsNullOrEmpty(openid))
            {
                content = content.TrimStart("\r\n".ToCharArray());
                string url = GetKFSend();
                openid.Split(',').ToList().ForEach(a =>
                {
                    JObject data = new JObject();
                    data.Add("touser", a);
                    data.Add("msgtype", "text");
                    data.Add("text", JObject.FromObject(new
                    {
                        content = content
                    }));


                    result = Utils.HttpHelper.PostJson(url, data.ToString());
                });
            }


            Common.LogHelper.WriteLog("微信消息发送>>>>>>", result);

            return result;
        }


        public string SendTemplateMsg(string openid, string content)
        {
            string url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + GetAccess_Token();

            JObject data = new JObject() { };
            JObject first = new JObject();
            first.Add("value", "服务器解析程序报警");
            first.Add("color", "#173177");

            data.Add("first", first);


            JObject keyword1 = new JObject();
            keyword1.Add("value", "开盒报警");
            keyword1.Add("color", "red");

            data.Add("keyword1", keyword1);

            JObject keyword2 = new JObject();
            keyword2.Add("value", "6000012119");
            keyword2.Add("color", "#173177");
            data.Add("keyword2", keyword2);

            JObject keyword3 = new JObject();
            keyword3.Add("value", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
            keyword3.Add("color", "#173177");
            data.Add("keyword3", keyword3);

            JObject keyword4 = new JObject();
            keyword4.Add("value", "设备开盒报警");
            keyword4.Add("color", "#173177");
            data.Add("keyword4", keyword4);


            JObject remark = new JObject();
            remark.Add("value", "您的设备出现开盒报警，请及时处理");
            remark.Add("color", "red");
            data.Add("remark", remark);




            JObject all = new JObject();
            all.Add("touser", openid);
            all.Add("template_id", "doaBGtXAmPVFm1DqK0eI8xX5I_kSWkYj7QvEEf0Mk2I");
            all.Add("url", "http://wx.4000600031.com/cameraweb/html/index.html");
            //all.Add("msgtype", "application/json");
            all.Add("topcolor", "#FF0000");
            all.Add("data", data);





            byte[] buffer = Encoding.UTF8.GetBytes(all.ToString());
            string msg = Encoding.UTF8.GetString(buffer, 0, buffer.Length);


            string result = Utils.HttpHelper.PostJson(url, msg);
            return result;
        }



        public string SendTemplateIpMsg(string openid, string content)
        {
            string result = "";
            if (!string.IsNullOrEmpty(openid) && !string.IsNullOrEmpty(content))
            {
                content = content.TrimStart("\r\n".ToCharArray());
                string url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + GetAccess_Token();
                openid.Split(',').ToList().ForEach(a =>
              {


                  JObject data = new JObject() { };
                  JObject first = new JObject();
                  first.Add("value", "服务器异常报警");
                  first.Add("color", "#173177");

                  data.Add("first", first);


                  JObject keyword1 = new JObject();
                  keyword1.Add("value", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));//故障时间
                  keyword1.Add("color", "red");
                  data.Add("keyword1", keyword1);

                  JObject keyword2 = new JObject();
                  keyword2.Add("value", ip);
                  keyword2.Add("color", "#173177");
                  data.Add("keyword2", keyword2);

                  JObject keyword3 = new JObject();
                  keyword3.Add("value", content);
                  keyword3.Add("color", "#173177");
                  data.Add("keyword3", keyword3);



                  JObject remark = new JObject();
                  remark.Add("value", "服务器监控程序异常，请及时处理");
                  remark.Add("color", "red");
                  data.Add("remark", remark);


                  JObject all = new JObject();
                  all.Add("touser", a);
                  all.Add("template_id", "V5duXwT1XCYvbORrXF1SepJA4Snxlb9Qci93_36evyo");
                  all.Add("url", "http://wx.4000600031.com/cameraweb/html/index.html");
                  //all.Add("msgtype", "application/json");
                  all.Add("topcolor", "#FF0000");
                  all.Add("data", data);
                  byte[] buffer = Encoding.UTF8.GetBytes(all.ToString());
                  string msg = Encoding.UTF8.GetString(buffer, 0, buffer.Length);
                  result = Utils.HttpHelper.PostJson(url, msg);

                  Common.LogHelper.WriteLog("微信模板发送>>>>>>", result);
              });
            }
            return result;
        }
        #endregion

       /// <summary>
       /// 获取系统开机时间
       /// </summary>
       /// <returns></returns>
        private DateTime GetComputerStartTime()
        {
            //int result = Environment.TickCount & Int32.MaxValue;  
            //TimeSpan m_WorkTimeTemp = new TimeSpan(Convert.ToInt64(Convert.ToInt64(result) * 10000)); 
            //DateTime startTime = System.DateTime.Now.AddDays(m_WorkTimeTemp.Days);
            //startTime = startTime.AddHours(-m_WorkTimeTemp.Hours);
            //startTime = startTime.AddMinutes(-m_WorkTimeTemp.Minutes);
            //startTime = startTime.AddSeconds(-m_WorkTimeTemp.Seconds); 
            //return startTime;    //返回转换后的时间
            DateTime dt = DateTime.Now.AddMilliseconds(0 - Environment.TickCount);
            return dt;
        }


        #region Item右键事件
        private void 打开目录ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var curRow = dataGridView1.CurrentRow;
            if (!string.IsNullOrEmpty(curRow.Cells[6].Value.ToString()))
            {
                try
                {
                    var path = curRow.Cells[6].Value.ToString().Substring(0, curRow.Cells[6].Value.ToString().LastIndexOf("\\"));
                    System.Diagnostics.Process.Start(path);
                    Common.LogHelper.Log("打开程序目录,名称：" + curRow.Cells[1].Value.ToString() + ",进程：" + curRow.Cells[2].Value.ToString() + ",路径：" + path);

                }
                catch (Exception ex) { }
            }
        }


        /// <summary>
        /// 右键点击选中行&显示右键菜单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridView1_CellMouseUp(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                if (e.RowIndex >= 0)
                {
                    dataGridView1.ClearSelection();
                    dataGridView1.Rows[e.RowIndex].Selected = true;
                    dataGridView1.CurrentCell = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex];
                    row_Menu.Show(MousePosition.X, MousePosition.Y);
                }
            }
        }

        private void 移除监控ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DataGridViewSelectedRowCollection items = dataGridView1.SelectedRows;
            foreach (DataGridViewRow item in items)
            {
                if ((!string.IsNullOrEmpty(item.Cells["StartTime"].Value.ToString())))
                {
                    string processname = "";
                    string processPath = "";
                    if (item.Cells["ProcessName"].Value != null)
                    {
                        processname = item.Cells["ProcessName"].Value.ToString();
                        processPath = item.Cells["ProcessPath"].Value.ToString();
                    }
                    if (setting.Pds.Any(a => a.ProcessName.Equals(processname) && a.ProcessPath.Equals(processPath)))
                    {
                        setting.Pds.Remove(setting.Pds.Single(a => a.ProcessName.Equals(processname) && a.ProcessPath.Equals(processPath)));

                        Common.LogHelper.Log("移除监控程序，名称：" + processname + ",路径：" + processPath);


                    }
                }
            }
            InvokeData();
            //toolStripProgressBar1.Value = 0;
            timer1_Tick(null, null);
        }

        [DllImport("user32.dll")]
        public static extern void SwitchToThisWindow(IntPtr hWnd, bool fAltTab);
        private void 前端显示ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                DataGridViewSelectedRowCollection items = dataGridView1.SelectedRows;
                foreach (DataGridViewRow item in items)
                {
                    string pName = item.Cells[2].Value.ToString();
                    string pPath = item.Cells[6].Value.ToString();

                    List<Process> temp = Process.GetProcessesByName(pName).ToList();//在所有已启动的进程中查找需要的进程； 
                    List<string> live = new List<string>(); 
                    if (temp.Count > 0)//如果查找到
                    {
                        foreach (var pro in temp)
                        {
                            if (pro.ProcessName.Equals(pName) && pro.MainModule.FileName.Equals(pPath))
                            {
                                IntPtr handle = pro.MainWindowHandle;
                                SwitchToThisWindow(handle, true); // 激活，显示在最前
                                //BindData(); 

                                if (!live.Exists(a => a == pro.ProcessName + pro.MainModule.FileName))
                                {
                                    Common.LogHelper.Log("前端显示程序，名称：" + pName + ",路径：" + pPath);
                                }
                                live.Add(pName + pPath);
                            }
                            else
                            {

                            }
                        }
                    }

                }
            }
            catch (Exception ex) 
            {
                MessageBox.Show(ex.Message + "   |   " + ex.StackTrace);
            }
        }

        private void 停止监控ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DataGridViewSelectedRowCollection items = dataGridView1.SelectedRows;
            foreach (DataGridViewRow item in items)
            {
                string processname = "";
                string processPath = "";
                if (item.Cells["ProcessName"].Value != null)
                {
                    processname = item.Cells["ProcessName"].Value.ToString();
                    processPath = item.Cells["ProcessPath"].Value.ToString();
                }

                if (setting.Pds.Any(a => a.ProcessName.Equals(processname) && a.ProcessPath.Equals(processPath)))
                {
                    setting.Pds.Single(a => a.ProcessName.Equals(processname) && a.ProcessPath.Equals(processPath)).Monitor = false;
                    Common.LogHelper.Log("停止监控程序，名称：" + processname + ",路径：" + processPath);
                }

                //if (setting.Pds.Select(a => a.ProcessName).ToList().IndexOf(processname) >= 0)
                //{
                //    setting.Pds.Single(a => a.ProcessName.Equals(processname) && a.ProcessPath.Equals(processPath)).Monitor = false;
                //}
            }
            // BindData();

            timer1_Tick(null, null);
        }

        private void 开始监控ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DataGridViewSelectedRowCollection items = dataGridView1.SelectedRows;
            foreach (DataGridViewRow item in items)
            {
                string processname = "";
                string processPath = "";
                if (item.Cells["ProcessName"].Value != null)
                {
                    processname = item.Cells["ProcessName"].Value.ToString();
                    processPath = item.Cells["ProcessPath"].Value.ToString();
                }
                if (setting.Pds.Any(a => a.ProcessName.Equals(processname) && a.ProcessPath.Equals(processPath)))
                {
                    setting.Pds.Single(a => a.ProcessName.Equals(processname) && a.ProcessPath.Equals(processPath)).Monitor = true;

                    Common.LogHelper.Log("开启程序监控，名称：" + processname + ",路径：" + processPath);
                }
            }
            //BindData();

            // toolStripProgressBar1.Value = 0;//进度20
            timer1_Tick(null, null);
        }


        #endregion

        #region
        private void btClear_Click(object sender, EventArgs e)
        {
            this.tbSearch.Text = string.Empty;
            InvokeData();

        }

        private void btSearch_Click(object sender, EventArgs e)
        {
            InvokeData();
        }

        #endregion
    }
    public class Token
    {
        public string access_token { get; set; }
        public int expires_in { get; set; }
    }

}
